<!-- 
  * Copyright (c) 2022 iSoftStone Information Technology (Group) Co.,Ltd.
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
  * You may obtain a copy of the License at
  *
  *     http://www.apache.org/licenses/LICENSE-2.0
  *
  * Unless required by applicable law or agreed to in writing, software
  * distributed under the License is distributed on an "AS IS" BASIS,
  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  * See the License for the specific language governing permissions and
  * limitations under the License.
 -->
<template>
	<view class="mainContent">
		<u-form :model="form" :rules="rules" ref="form" labelPosition="left" labelWidth="180rpx">
			<u-form-item label="活动名称" borderBottom>
				<u--text text="OpenHarmony开源开发者成长计划解决方案学生挑战赛" align="right"></u--text>
				<!-- <u--text :text="activityName" align="right"></u--text> -->
			</u-form-item>
			<u-form-item label="项目名称" prop="signupReason" borderBottom>
				<u-input :showWordLimit="true" type="text" :disabled="isDisabled" v-model="form.signupReason"
					maxlength="20" inputAlign="right" border="surround" placeholder="请创建项目名称">
				</u-input>
			</u-form-item>
			<u-form-item label="渠道来源" prop="way" borderBottom>
				<u--text :text="form.way?form.way:'请选择渠道'" suffixIcon="arrow-right" lines="1" margin="10px 0"
					align="right" @click="showPick=true">
				</u--text>
			</u-form-item>
			<!-- <view class="form-labe">
				<u--text text="(非必填项)请问您是从哪个渠道了解到此活动的？" lines="3"></u--text>
				<u--text text="请选择渠道 " suffixIcon="arrow-right" margin="10px 0" align="right" @click="showPick=true">
				</u--text>
			</view> -->
			<u-form-item label="手机号码" borderBottom>
				<u--text :text="ActiveLeaderData.phone" align="right" margin="10px 0"></u--text>
			</u-form-item>
			<u-form-item label="组队报名">
				<u-switch slot="right" :disabled="isDisabled" v-model="value" @change="change"></u-switch>
			</u-form-item>
			<u--text text="团队负责人填写队员手机号进行组队" type="info" size="12px" margin="-10px 15px 10px 15px" align="left">
			</u--text>
			<view style="border-top:0.5rpx solid #EAEBEC"></view>
			<view v-if="show">
				<view v-for="(item,index) in phoneList" :key="index">
					<u-form-item :label="'队员'+(index+1) "></u-form-item>
					<u-form-item label=" " labelWidth="0px !important">
						<u-input type="number" maxlength="11" :disabled="isDisabled" v-model="phoneList[index]"
							@blur="cell()" border="surround" placeholder="请填写正确的手机号">
						</u-input>
						<image @click="deleteTeams(item)" class="img-icon" src="../../static/icon/dele.png"></image>
					</u-form-item>
				</view>
				<view v-if="!isDisabled" @click="addTeams()" class="newAdd">添加队员</view>
			</view>
			<u-form-item label=" " prop="privacy" labelWidth="0px !important">
				<view class="labelBox">
					<view class="labelCheck">
						<u-checkbox-group placement="column" v-model="form.privacy">
							<u-checkbox labelSize="24rpx" shape="square" :disabled="isDisabled" label=" " name="1">
							</u-checkbox>
						</u-checkbox-group>
					</view>
					<view class="text">
						<text style="font-size:24rpx">同意OpenHarmony开源开发者成长计划-解决方案学生挑战赛</text>
						<text style="font-size:24rpx;">活动声明条款</text>
						<text style="font-size:24rpx">及</text>
						<text style="font-size:24rpx;color: #398ADE;" @click="gotoCompete()">赛制说明</text>
					</view>
				</view>
			</u-form-item>
			<view class="bottom">
				<u-button shape="circle" type="primary" :disabled="isDisabled" @click="submitBtn()">{{ stateDesc }}
				</u-button>
			</view>
			<template>
				<u-picker :show="showPick" ref="uPicker" :columns="columns" @confirm="confirm" @change="changeHandler"
					@cancel="showPick=false">
				</u-picker>
			</template>
		</u-form>

	</view>
</template>

<script>
	import {
		getActiveById,
		getVideoList,
		addActiveSignUp,
		getRegistrateId,
		addActiveWork,
		getStudentByOpenId,
		appletSignupCheckEdit,
		editActiveSignUp,
		getopenId,
		userLogin,
		getUserByOpenId,
		userEdit,
		usersave,
		getActiveLeader
	} from '@/common/api.js';
	export default {
		props: {
			activityId: Number,
			time: Number
		},
		data() {
			return {
				value: false,
				showPick: false,
				columns: [
					['三方社区', '官方渠道', "其他"],
					['51CTO', 'CSDN', 'InfoQ', '电子发烧友（硬声）', '开源中国', '其他三方社区']
				],
				columnData: [
					['51CTO', 'CSDN', 'InfoQ', '电子发烧友（硬声）', '开源中国', '其他三方社区'],
					['OpenHarmony官网', 'OpenHarmony官微', 'OpenHarmony社群', '其他官方渠道'],
					['搜索引擎', '他人推荐', '朋友圈', '学校群', '其他'],

				],
				text: "请选择渠道",
				form: {
					privacy: [],
					projectName: "",

				},
				phoneList: [""],
				phone: "",
				activityName: "",
				show: false,
				teamList: 1,
				n: 1,
				message: "",
				rules: {
					signupReason: {
						required: true,
						message: '请输入项目名称',
						trigger: ['blur', "change"]
					},
					privacy: {
						type: 'array',
						required: true,
						message: '请先查看并同意赛制及说明',
						trigger: ['change']
					},
					way: {
						required: true,
						message: '请选择渠道',
						trigger: ['change']
					}
				},
				isDisabled: false,
				stateDesc: '提交', // 底部按钮操作描述
				data: {},
				studentState: 0,
				uid: 0,
				loginType: 0,
				userInfo: {},
				WxData: {
					nickName: "请登录",
					avatarUrl: "",
					state: "请登录"
				},
				ActiveLeaderData: {},


			}
		},

		watch: {
			time: { //深度监听，可监听到对象、数组的变化
				handler(val, oldVal) {
					console.log(val, "报名时间发生变化")
					this.info()
				},
				deep: true //true 深度监听
			},
		},
		mounted() {
			this.info()
		},
		methods: {
			info() {
				this.userInfo = this.$store.state.$userInfo
				if (!this.userInfo.openId) {
					this.loginType = 0

				} else if (!this.userInfo.phone) {
					this.loginType = 1
				} else {
					this.loginType = 2
					this.phone = this.$store.state.$userInfo.phone
					this.ActiveLeaderData.phone = this.$store.state.$userInfo.phone
					this.getActiveLeader() //获取队长信息
					this.getActiveById() //获取活动详情
					//this.getRegistrateId() //获取报名详情
					//this.getStudentByOpenId() //获取学生详情
				}

			},
			getActiveLeader() {
				let data = {
					"activityId": this.activityId - 0,
					"phone": this.phone,
					"state": 1
				}
				getActiveLeader(data).then(res => {
					if (res.id) {
						data.userId = res.id
						this.ActiveLeaderData = res
						return getRegistrateId(data)
					}
				}).then(res => {
					console.log(res, "报名信息")
					if (res.id) {
						this.isDisabled = true
						this.form = res
						this.value = res.team === 2 ? true : false
						this.show = res.team === 2 ? true : false
						if (res.groupPhone && res.groupPhone.indexOf(",") !== -1) {
							this.form.phoneList = res.groupPhone.split(",")
							this.phoneList = []
							this.form.phoneList.forEach((item, index) => {
								if (index > 0 && item) {
									this.phoneList.push(item)
								}
							})
						}
						this.getcheckState(res.checkState)
					}
				})


			},
			getRegistrateId() {
				const data = {
					activityId: this.activityId - 0,
					userId: this.$store.state.$userInfo.id
				}
				getRegistrateId(data).then(res => {
					if (res.id) {
						this.isDisabled = true
						this.form = res
						this.value = res.team === 2 ? true : false
						this.show = res.team === 2 ? true : false
						if (res.groupPhone && res.groupPhone.indexOf(",") !== -1) {
							this.form.phoneList = res.groupPhone.split(",")
							this.phoneList = []
							this.form.phoneList.forEach((item, index) => {
								if (index > 0 && item) {
									this.phoneList.push(item)
								}
							})
						}
						this.getcheckState(res.checkState)
					}
				})
			},
			getActiveById() {
				const data = {
					id: this.activityId
				}
				getActiveById(data).then(res => {
					if (res.id) {
						this.activityName = res.name
					}
				})
			},
			getStudentByOpenId() {
				const data = {
					openId: this.$store.state.$userInfo.openId
				}
				getStudentByOpenId(data).then(res => {
					if (res.id) {
						console.log(res, "11111")
						this.studentState = res.check_state
						//this.stateDesc = checkState
						if (this.studentState === 1) {
							this.stateDesc = "学生信息审核中"
						} else if (this.studentState === 3) {
							this.stateDesc = "学生信息驳回"
						}
					} else {
						this.stateDesc = "学生信息未录入"
					}
				})
			},
			change() {
				this.show = !this.show
			},
			//新增队员
			addTeams() {
				if (this.phoneList.length < 6) {
					this.phoneList.push("")
				} else {
					uni.$u.toast("组队成员不能多于6人")
				}
			},
			//删除队员
			deleteTeams(item) {
				if (!this.isDisabled && this.phoneList.length > 1) {
					this.phoneList.splice(item, 1)
				}
			},
			//校验手机号码
			cell(item) {
				if (item) {
					console.log(item)
					const isphone = uni.$u.test.mobile(item)
					if (!isphone) {
						uni.$u.toast('手机号不正确')
						this.phoneList.forEach((res, index) => {
							if (res === item) {
								this.phoneList[index] = ''
								this.phoneList = [...this.phoneList]
							}
						})
					}
				}
			},
			//提交
			submitBtn() {
				if (this.loginType === 0) {
					this.loginWx()
					return false
				} else if (this.loginType === 1) {
					this.showModalPhone()
					return false
				}
				this.saveSigin()
				/* console.log(this.studentState)
				if (this.studentState === 0) {
					this.showM("您未录入学生信息，请先录入学生信息")
				} else if (this.studentState === 1) {
					uni.$u.toast("学生信息审核中!")
				} else if (this.studentState === 2) {
					this.saveSigin()
				} else if (this.studentState === 3) {
					this.showM("学生信息已驳回请重新提交！")
				} */

			},
			showM(content) {
				const that = this
				uni.showModal({
					confirmText: "去录入",
					cancelText: "取消",
					content: content,
					cancelColor: "#8F8F94",
					confirmColor: "#3C9CFF",
					success: function(res) {
						if (res.confirm) {
							that.$u.route({
								url: 'pages/componet/main/students/index',
							})
						}
					}
				})
			},
			saveSigin() {
				this.$refs.form.validate().then(res => {
					let data = {
						activityid: this.activityId,
						groupPhone: this.phone + "," + this.phoneList.toString(),
						team: this.value ? 2 : 1,
						signupid: this.$store.state.$userInfo.id,
						signupReason: this.form.signupReason,
						id: this.form.id ? this.form.id : 0,
						way: this.form.way
					}

					const _self = this
					uni.showModal({
						content: "是否参与报名，提交后数据暂时不能修改",
						success: (result) => {
							if (result.confirm) {
								_self.isDisabled = true
								if (_self.stateDesc === "再次提交") {
									data.checkState = 1
									editActiveSignUp(data).then(res => {
										data.id = this.form.recordId
										appletSignupCheckEdit(data).then(res => {
											_self.stateDesc = "待审核"
										})
									})
								} else {
									addActiveSignUp(data).then(res => {
										_self.stateDesc = "待审核"

									})
								}
							}
						}
					})


				})

			},
			//跳转赛事说
			gotoCompete() {
				this.$emit("change", 2)
			},
			changeData() {
				console.log(this.data, "获取数据")
			},
			getcheckState(state) {
				let checkState = null
				if (state === 1) {
					checkState = "待审核"
					this.isDisabled = true
					this.form.privacy = ["1"]
				} else if (state === 2) {
					checkState = "审核通过"
					this.isDisabled = true
					this.form.privacy = ["1"]
				} else if (state === 3) {
					checkState = "再次提交"
					this.isDisabled = false
				} else {
					checkState = "提交"
				}
				this.stateDesc = checkState
				this.getStudentByOpenId()
			},
			changeHandler(e) {
				const {
					columnIndex,
					value,
					values, // values为当前变化列的数组内容
					index,
					// 微信小程序无法将picker实例传出来，只能通过ref操作
					picker = this.$refs.uPicker
				} = e
				// 当第一列值发生变化时，变化第二列(后一列)对应的选项
				if (columnIndex === 0) {
					// picker为选择器this实例，变化第二列对应的选项
					picker.setColumnValues(1, this.columnData[index])

				}
			},
			// 回调参数为包含columnIndex、value、values
			confirm(e) {
				console.log('confirm', e)
				this.form.way = e.value.toString()
				this.showPick = false
			},
			handelClose() {
				console.log(111)
				this.showPick = false
			},
			loginWx() {
				uni.getUserProfile({
					lang: 'zh_CN',
					desc: '用户登录', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
					success: (res) => {
						this.getOpenid(res)
					},
					// 失败回调
					fail: (err) => {
						// 弹出错误
						uni.showModal({
							content: '已拒绝小程序获取信息',
							showCancel: false
						})
					}
				});
			},
			getOpenid(res) {
				uni.login({
					success: (item) => {
						const data = {
							"code": item.code
						}
						getopenId(data).then(el => {
							if (el.openId) {
								res.userInfo.openId = el.openId
								this.WxData.avatarUrl = res.userInfo.avatarUrl
								this.WxData.nickName = res.userInfo.nickName
								this.WxData.openId = el.openId
								this.$store.commit("setUserInfo", res.userInfo)
								console.log(res.userInfo, "setUserInfo")
								uni.setStorage({
									key: 'userInfo',
									data: res.userInfo,
									success: function() {
										console.log("保存登录信息")
									}
								});
								this.getUserByOpenId(el.openId)
							}
						})
					},
				});
			},
			getUserByOpenId(openId) {
				//根据openId 获取用户信息，有信息登录，没有信息新增用户信息
				const data = {
					openId: openId
				}
				getUserByOpenId(data).then(res => {
					if (res.userName) {
						res.username = res.userName
						this.WxData.id = res.id
						this.$store.commit("setUserInfo", res)
						this.userLogin(res)
					} else {
						this.userAdd()
					}
				})
			},
			userAdd() {
				let data = {
					openId: this.$store.state.$userInfo.openId,
					nickName: encodeURI(this.$store.state.$userInfo.nickName),
					avatarUrl: this.$store.state.$userInfo.avatarUrl,
					inviteOpenId: this.$store.state.inviteOpenId
				}
				usersave(data).then(res => {
					if (res) {
						getUserByOpenId(data).then(result => {
							this.$store.commit("setUserInfo", result)
						})
						res.openId = data.openId
						this.userLogin(res)
					}
				})
			},
			userLogin(data) {
				userLogin(data).then(res => {
					if (res.token) {
						this.$store.commit("setUserToken", res.token)
						this.userEdit()
					}
				})
			},
			userEdit() {
				let data = {
					openId: this.WxData.openId,
					nickName: encodeURI(this.WxData.nickName),
					avatarUrl: this.WxData.avatarUrl,
					id: this.WxData.id
				}
				userEdit(data).then(res => {
					if (res) {
						//this.$store.commit("setUserInfo", res)
						this.info()
					}
				})

			},
			showModalPhone() {
				const that = this
				uni.showModal({
					content: "请完善您的个人信息",
					cancelText: "再想想",
					confirmText: "去编辑",
					success: function(res) {
						if (res.confirm) {
							that.$u.route({
								url: 'pages/componet/main/edit/edit'
							})
						}
					}
				})
			},

		}
	}
</script>

<style lang="scss" scoped>
	.txtlable {
		display: block;
	}

	.theme-title {
		text-align: center;
		padding-top: 20rpx;
		font-weight: bold;
		margin: 20rpx 0;
	}

	.mainContent {
		margin-top: 16rpx;
		background: #FFFFFF;
	}

	.switch {
		padding-top: 39rpx;
		padding-right: 24rpx;
	}

	.addTeam {
		margin: 30rpx 0 18rpx 24rpx;
		font-family: HarmonyHeiTi-Medium;
		font-size: 12px;
		color: rgba(0, 0, 0, 0.5);
	}

	.img-icon {
		width: 56rpx;
		height: 52rpx;
		margin: 14rpx 26rpx 0 36rpx;
		position: absolute;
		right: 1%;
		padding-top: 14rpx;
	}

	.newAdd {
		text-align: center;
		color: #0A59F7;
		font-family: HarmonyHeiTi;
		font-size: 32rpx;
		margin: 34rpx 40rpx 20rpx 40rpx;
	}

	.checkbox {
		padding: 16rpx 24rpx 16rpx 32rpx;

		.contentLabel {
			font-family: HarmonyHeiTi-Medium;
			font-size: 24rpx;
			color: rgba(0, 0, 0, 0.5);
			font-weight: bold;
		}
	}

	.bottom {
		width: 94%;
		margin-left: 3%;
		height: 128rpx;
		line-height: 128rpx;
		position: fixed;
		bottom: 0;
	}

	.labelBox {
		display: flex;
		flex-direction: row;

		.labelCheck {
			position: relative;
			top: 12rpx;
		}

		.text {
			width: calc(100% - 40px);
			display: block;

			text {
				display: inline !important;
			}
		}

	}

	.form-labe {
		padding: 40rpx 30rpx;
		font-size: 14px;
		color: #303133;
		border-bottom: 1px solid #d6d7d9;
	}
</style>
